<?php
namespace admin\action;

use api\utils\SaasApiClient;
use api\utils\PayApiClient;
use herosphp\core\Log;
use herosphp\core\WebApplication;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\string\StringUtils;
use herosphp\web\WebUtils;


class MemberAction extends CommonAction {

	public function C_start()
	{
		parent::C_start();
	}

	protected $serviceBean="member.member.service";

    /**
     * @param HttpRequest $request
     */
    public function index(HttpRequest $request)
    {
        $conditions = array('del_status' => 0);
        $s_username = $request->getParameter('s_keyword');
        $page = $request -> getParameter('page');
        if( !$page || $page<0 ){
            $page = 1;
        }
        $this -> setPage($page);
        $pagesize = $request->getParameter('pagesize') ? $request->getParameter('pagesize') : $this->getPagesize();
        $this->setPagesize($pagesize);
        $this->assign('s_keyword', $s_username);

        $s_type = $request->getParameter('s_type');
        $this->assign('s_type', $s_type);
        if ( $s_type == "2" ) {
            /*if ($s_username !== '' && $s_username !== NULL) {
                $params['name'] = '%' . $s_username . '%';
                $result = APIClient::send('api/user/getIdByName',$params);
                $data = $result -> getItems();
                $tmp = array(0);
                foreach ($data as $value) {
                    $tmp[] = $value['id'];
                }
                $conditions['dasu_pay_id'] = array('$in' => $tmp);
            }*/
            if ($s_username !== '' && $s_username !== NULL) $conditions['real_name'] = '%' . $s_username . '%';
        }elseif( $s_type == "1" ){
            if ($s_username !== '' && $s_username !== NULL) $conditions['username'] = '%' . $s_username . '%';
        }

        $s_s_reg_time = $request->getParameter('s_s_reg_time');
        $s_e_reg_time = $request->getParameter('s_e_reg_time');
        $this->assign('s_s_reg_time',$s_s_reg_time);
        $this->assign('s_e_reg_time',$s_e_reg_time);

        if($s_s_reg_time !== '' && $s_s_reg_time!== NULL){
            $conditions['addtime'] = array();
            $conditions['addtime']['>'] = $s_s_reg_time.' 00:00:00';
        }
        if($s_e_reg_time !== '' && $s_s_reg_time!== NULL){
            if(!$conditions['addtime']){ $conditions['addtime'] = array();}
            $conditions['addtime']['<='] = $s_e_reg_time.' 23:59:59';
        }

        $this->setConditions($conditions);
        $this -> setOrder("addtime desc");
        $service = Beans::get($this->getServiceBean());

        //导出Excel
        if($request->getParameter('export') == 1){
            $ids = $request -> getParameter('ids');
            if( $ids ){
                $this -> setConditions(array('id'=>array('$in'=>$ids)));
            }
            $exportItems = $service->getItems($this->getConditions(), $this->getFields(), $this->getOrder());
            $excel = array();
            foreach($exportItems as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["username"];
                $tmp[] = $v["total_cost"];
                $tmp[] = $v["real_name"];
                $tmp[] = $v["addtime"];
                $tmp[] = $v["last_trade_time"];
                $tmp[] = $v["group_name"];
                $tmp[] = $v["status"] == 1 ? "启用" : "禁用";
                $tmp[] = $v["last_login_ip"]?long2ip($v["last_login_ip"]):"";
                $excel[] = $tmp;
            }
            $header = array('会员账号','累计消费','实名认证','注册时间','最后交易时间','所属分组','状态','上次登陆ip');
            phpexcel("会员列表",$header,$excel);
            exit();
        }
        $total = $service->count($this->getConditions());
        $items = $service->getItems($this->getConditions(), $this->getFields(), $this->getOrder(),
            array($this->getPage(), $this->getPagesize()), $this->getGroup(), $this->getHaving());
        foreach($items as $k=>$v){
            $items[$k]['last_login_ip'] = $v['last_login_ip']?long2ip($v['last_login_ip']):'';
        }
        $this->generatePageMenu( $total );
        $this->assign('pagesize',$pagesize);
        $this->assign('items', $items);

        $this->setView('member/index');
        $this->assign("title", "会员列表");
        $this->assign('bread', array('会员管理',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
    }

    /**
     * 添加会员页面
     * @param HttpRequest $request
     */
	public function add(HttpRequest $request) {
	
		parent::add($request);

        $groupService = Beans::get("member.memberGroup.service");
        $groupItem = $groupService -> getGroupList();
		$this->assign("groupItem", $groupItem);
		$this->assign("title", "添加会员");
		$this->assign('bread', array('会员管理','会员列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/member/index'),'javascript:;'));
    }

    /**
     * 会员编辑页面
     * @param HttpRequest $request
     */
	public function edit(HttpRequest $request) {

        $id = $request->getParameter('id');
        if ( $id == '' ) {
            $this->showMessage('danger', COM_ERR_MSG);
        } else {
            $conditions['id'] = $id;
            $service = Beans::get($this->getServiceBean());
            $item = $service->getItemWithSignInfo($conditions);
            if( $item['card_no'] ){
                $item['card_no'] = substr_replace($item['card_no'], "***********", 4, 11);
            }
            $this->assign('id',$id);
            $this->assign('item', $item);
        }
        $this->setView(strtolower($request->getAction()).'/add');

        $groupService = Beans::get("member.memberGroup.service");
        $groupItem = $groupService -> getGroupList();

        //大塑支付信息
        $this->assign("groupItem", $groupItem);
		$this->assign("title", "编辑会员");
		$this->assign('bread', array('会员管理','会员列表',$this->getTemplateVar('title')));
		$this->assign('breadUrl', array('javascript:;',url('admin/member/index'),'javascript:;'));
	}


    /**
     * 添加会员
     * @param HttpRequest $request
     */
	public function do_add(HttpRequest $request)
	{
		$data = $request->getParameter('data');
        $data['password'] = md5(md5($data['password']));
        $data['nickname'] = 'mpe_'.substr($data['username'],5);
        $data['reg_time'] = date("Y-m-d H:i:s");
        $data['last_login_time'] = date("Y-m-d H:i:s");
        //$data['last_login_ip'] = WebUtils::getClientIP();
        $data['last_login_ip'] = "0";
        $data['addtime'] = date("Y-m-d H:i:s");
        $data['updatetime'] = date("Y-m-d H:i:s");
		//$data['last_login_ip'] = ip2long($data['last_login_ip']);
		$request->addParameter('data',$data);
        $service = Beans::get($this->getServiceBean());
        if( $service->count(array("username"=>$data['username'],"del_status"=>"0")) > 0 ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号已被注册",null);
        }

        //如果原来有这个账号就干掉,物理删除
        if( $service->count(array("username"=>$data['username'],"del_status"=>"1")) > 0 ){
            $service -> realDeletes(array("username"=>$data['username']));
        }
		parent::do_add($request);
	}

    /**
     * 编辑会员
     * @param HttpRequest $request
     */
	public function do_edit(HttpRequest $request){
		$data = $request->getParameter('data');

		if($data['password']==""){
		    unset($data['password']);
        }else{
            $data['password'] = passwd($data['password']);
        }
        $service = Beans::get($this->getServiceBean());
        $total = $service->count(array("username"=>$data['username'],"del_status"=>"0"));
        if( $total > 1 ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号已被注册",null);
        }
		$request->addParameter('data',$data);
		parent::do_edit($request);	
	}

    /**
     * 绑定大塑支付
     * @param HttpRequest $request
     *
     */
	public function do_bind(HttpRequest $request){
        $params = $request -> getParameter('data');
        $params['password'] = md5($params['password']);
        $url = "api/user/bind";
        $result = PayApiClient::send($url, $params);
        if ( $result->isSucess() ) {
            $items = $result->getItem();
            if( $items['sign_status'] != 1 ){
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号未签约，请更换新的账号",null);
            }
            $service = Beans::get($this->getServiceBean());
            if($service->count(array('dasu_pay_id' => $items['id'],'del_status'=>0)) > 0)
            {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该账号已被绑定，请更换新的账号",null);
            }
            $data['dasu_pay_id'] = $items['id'];
            if( $items['ischecked'] ==2 ){
                $data['real_name'] = $items['virtual_name'];
                $data['ischecked'] = 1;
                $data['sign_status'] = $items['sign_status'];
            }

            $data['updatetime'] = date('Y-m-d H:i:s');
            $id = $params['app_userid'];

            if ( $service->update($data, $id) ) {
                $this -> log("用户{$params['id']}绑定到大塑账户：{$params['username']}","绑定大塑账户");
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, '绑定成功',null);
            } else {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '大塑账户或密码不正确',null);
            }
        } else {
            Log::error("MPE后台绑定大塑账户失败，接口返回：".$result->getMessage());
            AjaxResult::ajaxFailtureResult();
        }
    }

    public function deletes(HttpRequest $request){
        parent::deletes($request);
    }

    /**
     * 批量启用/禁用
     * @param HttpRequest $request
     */
    public function do_updateStatus(HttpRequest $request){
        $type = $request -> getParameter('type');
        if( $type=="" ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"操作失败",null);
        }
        $ids = $request->getParameter('ids');
        if ( empty($ids) ) AjaxResult::ajaxResult('error', COM_ERR_MSG);
        $service = Beans::get($this->getServiceBean());

        if( $type == 1 ){
            $service->updates(array('status'=>1,'session_id'=>""),array('id' => array('$in' => $ids)));
            AjaxResult::ajaxSuccessResult();
        }else{
            $service->updates(array('status'=>0,'session_id'=>""),array('id' => array('$in' => $ids)));
            AjaxResult::ajaxSuccessResult();
        }

    }
}
